package com.cqemme.hardwareservice.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cqemme.comm.constraint.MqNames;
import com.cqemme.comm.enums.AlarmType;
import com.cqemme.comm.po.Result;
import com.cqemme.comm.utils.DateUtils;
import com.cqemme.comm.utils.JackSonUtils;
import com.cqemme.comm.utils.ResultCodeMsg;
import com.cqemme.comm.utils.StringUtils;
import com.cqemme.hardwareservice.feign.SchoolServiceFeign;
import com.cqemme.hardwareservice.po.AccessRecordPo;
import com.cqemme.hardwareservice.po.EarlyWarningPo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;


/**
 *
 * @author 86156
 */
@Api(value = "人脸设备-出入记录",tags = "人脸设备-出入记录")
@RestController
@RequestMapping("/face")
@Slf4j
public class FaceRecognitionSystemController {

    @Autowired
    private SchoolServiceFeign schoolServiceFeign;
    @Autowired
    private AmqpTemplate amqpTemplate;
    private static final String Params_Si_org_code = "siOrgCode";
    private static final String default_code = "0";
    private static final String Params_unusualTimes = "unusualTimes";
    private static final String Params_start = "start";
    private static final String Params_end = "end";
    @ApiOperation(value = "三方调用出入记录 此接口推向MQ 然后由mango处理", notes = "Tommy")
    @RequestMapping(value = "/receiveAccessRecord", method = RequestMethod.POST)
    @ResponseBody
    public Result receiveAccessRecord(@RequestBody String infos) {
        Result result = new Result();
        log.info("出入记录调用方法进入：====》"+infos);
        AccessRecordPo info = JackSonUtils.strToBean(infos,AccessRecordPo.class);
        log.info("请求json字符串："+JackSonUtils.beanToString(info));
        String deviceNumber = "";
        try {
            if(info!=null){
                Result thr = schoolServiceFeign.queryByTenantIdAndDeviceId(Integer.parseInt(info.getTenantId()),Integer.parseInt(info.getDeviceId()));
                log.info("内部调用1："+JackSonUtils.beanToString(thr));
                if(thr.getStatusCode()==ResultCodeMsg.CODE_200){
                  JSONObject json = JSONObject.parseObject(thr.getData().toString());
                   deviceNumber =  json.getString("deviceNumber");
                  if(json.getInteger(Params_Si_org_code)!=null){
                      info.setOrgCode(json.getInteger(Params_Si_org_code).toString());
                  }else{
                      info.setOrgCode(default_code);
                  }
                }else{
                    info.setOrgCode(default_code);
                }
                Result result1 = schoolServiceFeign.queryByOrgAndWeekNum(Integer.parseInt(info.getOrgCode()), DateUtils.getWeekNumber(DateUtils.parseDateForRobotization(info.getCreateTime())));
                log.info("内部调用2："+JackSonUtils.beanToString(result1));
                if(result1.getStatusCode()==ResultCodeMsg.CODE_200){
                    String data = result1.getData().toString();
                    JSONObject json=JSONObject.parseObject(data);
                    if(StringUtils.checkIsNotNull(json.get(Params_unusualTimes))){
                        JSONArray jr = JSONArray.parseArray(json.get(Params_unusualTimes).toString());
                        for (int i = 0; i < jr.size(); i++) {
                            JSONObject st = jr.getJSONObject(i);
                            if(st!=null&&DateUtils.isEffectiveDate(DateUtils.parseDateForRobotizationHhmmss(info.getCreateTime()),DateUtils.parseDateForRobotizationHhmmss(st.getString(Params_start)),DateUtils.parseDateForRobotizationHhmmss(st.getString(Params_end)))){
                                info.setUnusual(true);
                                log.info("true");
                                break;
                            }
                        }
                    }
                }
                /**
                 * 异常进行消息推送--推送队列 然后由消息服务获取进行转发相关用户
                 */
                if(info.isUnusual()){
                    amqpTemplate.convertAndSend(MqNames.SEND_ERROR_ACCESS_RECORD_INFO,JackSonUtils.beanToString(info));
                    Map<String,Object> cmap = new HashMap<>();
                    cmap.put("type", AlarmType.MJ_ILLEGAL_ACCESS.getKey());
                    Map<String,Object> mapc2 = new HashMap<>();
                    mapc2.put("deviceNumber",deviceNumber);
                    mapc2.put("info",info);
                    cmap.put("data",mapc2);
                    amqpTemplate.convertAndSend(MqNames.SCHOOL_HARDWARE_TO_ACTIVITI_ALARM,JackSonUtils.beanToString(cmap));
                }
                amqpTemplate.convertAndSend(MqNames.ACCESS_RECORD_INFO, JackSonUtils.beanToString(info));
                amqpTemplate.convertAndSend(MqNames.ES_ACCESS_RECORD_INFO,JackSonUtils.beanToString(info));
                result.setStatusCode(ResultCodeMsg.CODE_200);
            }else{
                result.setStatusCode(ResultCodeMsg.CODE_501);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            result.setStatusCode(ResultCodeMsg.CODE_500);
        }
        return result;
    }

    @ApiOperation(value = "三方调用预警记录 此接口推向MQ 然后由mango处理", notes = "Tommy")
    @RequestMapping(value = "/receiveEarlyWarning", method = RequestMethod.POST)
    @ResponseBody
    public Result receiveAccessRecord(@RequestBody EarlyWarningPo info) {
        Result result = new Result();
        try {
            if(info!=null){
                Result thr = schoolServiceFeign.queryByTenantIdAndDeviceId(Integer.parseInt(info.getTenantId()),Integer.parseInt(info.getDeviceId()));
                if(thr.getStatusCode()==200){
                    JSONObject json = JSONObject.parseObject(thr.getData().toString());
                    if(json.getInteger(Params_Si_org_code)!=null){
                        info.setOrgCode(json.getInteger(Params_Si_org_code).toString());
                    }else{
                        info.setOrgCode(default_code);
                    }
                }else{
                    info.setOrgCode(default_code);
                }
                amqpTemplate.convertAndSend(MqNames.EARLY_WARNING_RECORD_INFO, JackSonUtils.beanToString(info));
                amqpTemplate.convertAndSend(MqNames.ES_EARLY_WARNING_RECORD_INFO, JackSonUtils.beanToString(info));
                result.setStatusCode(ResultCodeMsg.CODE_200);
            }else{
                result.setStatusCode(ResultCodeMsg.CODE_501);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            result.setStatusCode(ResultCodeMsg.CODE_500);
        }
        return result;
    }
}
